function p = pinvc(a)
% pinvc  - pseudo-inverse using svdc
%
% FORMAT:       p = pinvc(a)
%
% Input fields:
%
%       a           numeric matrix, with at least as many rows as columns
%
% Output fields:
%
%       p           pseudo-inverse of matrix
%
% Note: this function makes use of a different implementation of SVD!

% Version:  v0.7f
% Build:    8112421
% Date:     Nov-24 2008, 9:30 PM CET
% Author:   Jochen Weber, SCAN Unit, Columbia University, NYC, NY, USA
% URL/Info: http://wiki.brainvoyager.com/BVQXtools

% argument check
if nargin ~= 1 || ...
   ~isa(a, 'double') || ...
    isempty(a) || ...
    ndims(a) > 2 || ...
    size(a, 1) < size(a, 2)
    error( ...
        'BVQXtools:BadArgument', ...
        'Bad or missing argument.' ...
    );
end

% get svd with svdc
[U, S, V] = svdc(a);

% compute diagonal elements of S as 1 ./ S
sz = size(S, 1) + 1;
sd = 1 ./ S(1:sz:end);

% reject values < a reasonable tolerance
sd(isinf(sd) | isnan(sd) | sd > 1e14) = 0;
S(1:sz:end) = sd;

% compute pseudo-inverse
p = V * S * U';
